package com.ac.api.userinfo.controller;

import com.ac.api.user.entity.AcUser;
import com.ac.api.user.service.AcUserService;
import com.ac.utils.JWTUtil;
import com.ac.utils.OssUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.RequestMapping;
import com.base.annotation.SysLog;
import org.springframework.web.bind.annotation.RestController;
import com.base.helper.BaseController;
import com.base.helper.Result;
import com.ac.api.userinfo.entity.AcUserinfo;
import com.ac.api.userinfo.service.AcUserinfoService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lyj
 * @since 2025-03-14
 */
@Api(tags = "AcUserinfo")
@RestController
@RequestMapping("/acUserinfo")
public class AcUserinfoController extends BaseController {

        private static final Logger       LOG = LoggerFactory.getLogger(AcUserinfoController.class);
        @Autowired
        private              AcUserinfoService entityService;
        @Autowired
        private AcUserService userService;

        @SysLog(action = "findByPage", value = "分页查询用户个人信息")
        @ApiOperation(value = "分页查询用户个人信息", notes = "分页查询用户个人信息")
        @RequestMapping(method = RequestMethod.GET)
        @ApiImplicitParams({@ApiImplicitParam(name = "size", value = "分页大小", paramType = "query"),
                @ApiImplicitParam(name = "current", value = "当前页面：从1开始", paramType = "query")})
        public Result<IPage<AcUserinfo>> findByPage(final AcUserinfo example, final Page page) {
            IPage<AcUserinfo>        records    = entityService.page(example,page);
            return new Result(true, records);
        }

        @SysLog(action = "delete", value = "删除用户个人信息")
        @ApiOperation(value = "删除用户个人信息")
        @RequestMapping(value = "{id}", method = {RequestMethod.DELETE})
        @ApiImplicitParam(name = "id", value = "用户个人信息ID", required = true, paramType = "path")
        public Result delete(@PathVariable final Integer id) {
            try {
                entityService.removeById(id);
                return new Result(true, "成功删除用户个人信息", null);
            } catch (DataIntegrityViolationException e) {
                LOG.error("删除用户个人信息失败", e);
                return new Result(false, "删除用户个人信息失败", "该用户个人信息不能删除，存在其他关联数据");
            } catch (Exception e) {
                LOG.error("删除用户个人信息失败", e);
                return new Result(false, "删除用户个人信息失败", e.getMessage());
            }
        }

        @SysLog(action = "one", value = "查询用户个人信息")
        @ApiOperation(value = "查询用户个人信息")
        @RequestMapping(value = "{id}", method = {RequestMethod.GET})
        public Result one(HttpServletRequest request) {
            try {
                String token = request.getHeader("Authorization");
                Map<String, Object> c = JWTUtil.parseToken(token);
                Integer ID = (Integer) c.get("id");

                // 创建QueryWrapper实例，用于构建查询条件
                QueryWrapper<AcUserinfo> queryWrapper = new QueryWrapper<>();
                // 设置查询条件：userid等于路径参数中的userid
                queryWrapper.eq("userid", ID);
                // 使用MyBatis-Plus的方法进行查询
                AcUserinfo entity = entityService.getOne(queryWrapper);
                return new Result(true, entity);
            } catch (Exception e) {
                LOG.error("查询用户个人信息失败", e);
                return new Result(false, new AcUserinfo());
            }
        }

        @SysLog(action = "add", value = "添加用户个人信息")
        @ApiOperation(value = "添加用户个人信息")
        @RequestMapping(method = {RequestMethod.POST})
        public Result add(@Valid @RequestBody final AcUserinfo entity, final BindingResult result,HttpServletRequest request) {
            try {
                if (result.hasErrors()) {
                    Map<String, String> map      = this.getErrors(result);
                    String              errorMsg = map.entrySet().iterator().next().getValue();
                    return new Result(false, "保存用户个人信息失败", errorMsg, map);
                } else {
                    String token = request.getHeader("Authorization");
                    Map<String, Object> c = JWTUtil.parseToken(token);
                    Integer ID = (Integer) c.get("id");
                    entity.setUserid(ID);
                    entityService.save(entity);
                    return new Result(true, "成功用户个人信息订单", null);
                }
            } catch (Exception e) {
                LOG.error("添加用户个人信息失败", e);
                return new Result(false, "保存用户个人信息失败", e.getMessage());
            }
        }

        @ApiOperation(value = "全部用户个人信息")
        @RequestMapping(value = "all", method = RequestMethod.GET)
        public Result<List<AcUserinfo>> all(AcUserinfo example) {
            List<AcUserinfo> entitys = entityService.list(example);
            if (null != entitys) {
                return new Result<>(true, entitys);
            }
            return new Result<>(true, Collections.emptyList());
        }
        //修改用户头像
        @SysLog(action = "update", value = "修改用户头像")
        @ApiOperation(value = "修改用户头像")
        @RequestMapping(value = "updateAvatar", method = {RequestMethod.POST})
        public Result updateAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
            try {
                String token = request.getHeader("Authorization");
                Map<String, Object> c = JWTUtil.parseToken(token);
                Integer ID = (Integer) c.get("id");
                String picture = OssUtil.uploadImage(file, ID + LocalTime.now().toString());
                QueryWrapper<AcUser> queryWrapper = new QueryWrapper<>();
                // 设置查询条件：userid等于路径参数中的userid
                queryWrapper.eq("id", ID);
                //将picture字段更新
                return new Result(true, userService.update(new AcUser(), queryWrapper));
                } catch (Exception e) {
                    LOG.error("修改用户头像失败", e);
                    return new Result(false, "修改用户头像失败", e.getMessage());
                }
            }
            //修改用户Userinfo信息和user信息
            @SysLog(action = "update", value = "修改用户个人信息")
            @ApiOperation(value = "修改用户个人信息，用户生日形式2004-04-07")
            @RequestMapping(value = "updateUserinfo", method = {RequestMethod.POST})
            public Result updateUserinfo(@RequestParam("username") String username,
                                         HttpServletRequest request,
                                         @RequestParam("userbiography") String userbiography,
                                         @RequestParam("userweight")Integer userweight,
                                         @RequestParam("usertall")Integer usertall,
                                         @RequestParam("userbrithday")String userbrithday,
                                         @RequestParam("usergender") String usergender) {
                try {
                    String token = request.getHeader("Authorization");
                    Map<String, Object> c = JWTUtil.parseToken(token);
                    Integer ID = (Integer) c.get("id");
                    LocalDate userbrithday1 = LocalDate.parse(userbrithday);
                    //username属于user，其余属于userinfo表
                    return new Result(true, userService.update(new AcUser().setUsername(username), new QueryWrapper<AcUser>().eq("id", ID))
                            && entityService.update(new AcUserinfo().setUserbiography(userbiography).setUserweight(userweight).setUsertall(usertall)
                            .setUserbrithday(userbrithday1).setUsergender(usergender)
                            .setUpdataTime(LocalDateTime.now()), new QueryWrapper<AcUserinfo>().eq("userid", ID)));
                }
                catch (Exception e) {
                    LOG.error("修改用户个人信息失败", e);
                    return new Result(false, "修改用户个人信息失败", e.getMessage());
                }
            }
 }

